const fs = require('fs')
const path = require('path')
const mdContainer = require('markdown-it-container')
const makeDir = require('make-dir')
const { getImportStr } = require('../../utils/ImportUtil')

/**
 * vuepress v0.x~1.x~
 * @param {*} options
 * @return {*}
 */
function pluginOptionsV1(options) {
  // 缓存路径
  let vueDirTemp = options['vueDirTemp']
  // 导入组件列表
  let importCodeList = options['importCodeList']
  // container容器的名称
  let demoBlockName = options['demoBlockName']

  return {
    // webapck配置
    chainWebpack: (config, isServer) => {
      // config 是 ChainableConfig 的一个实例
      // console.log('config.loader():', config.module.rules.store.get('sass'))
      if (!isServer) {
        config.resolve.modules.merge(['node_modules'])
      }
      return config
    },
    // 该 Hook 中的文件会在客户端 App 创建后被调用
    // 路径分隔符绝对不能是\，使用const path = require('path')就是\分割符，会报错，@vuepress/utils的分隔符是/
    enhanceAppFiles: path.resolve(__dirname, '../client/clientAppEnhance.js').replace(/\\/g, '/'),
    // 渲染Markdown
    extendMarkdown: (md) => {
      md.use(mdContainer, demoBlockName, {
        validate(params) {
          let exp = new RegExp(`^${demoBlockName}\s*(.*)$`)
          return !!params.trim().match(exp)
        },
        render: (tokens, index, options, env, self) => {
          // 检测到这个type容器的文件路径信息
          // 开始标签
          if (tokens[index].nesting === 1) {
            // 1.获取第一行的内容使用markdown渲染html作为组件的描述
            let exp = new RegExp(`^${demoBlockName}\s*(.*)$`)
            let demoInfo = tokens[index].info.trim().match(exp)
            let description = demoInfo && demoInfo.length > 1 ? demoInfo[1] : ''

            let descriptionHTML = description ? md.render(description) : ''

            // 2.获取代码块内的html和js代码
            let content = tokens[index + 1].content

            let filePathRelative = env['relativePath']

            let fileObj = path.parse(filePathRelative)

            let dirPath = path.join(vueDirTemp, fileObj['dir'])
            makeDir.sync(dirPath)
            let compName = (fileObj['name'] + index).toLocaleLowerCase()
            let vueFilePath = path.join(dirPath, `${compName}.vue`)

            fs.writeFileSync(vueFilePath, content)

            // console.log('缓存vue文件：', vueFilePath, descriptionHTML)

            if (typeof descriptionHTML === 'object') {
              descriptionHTML = descriptionHTML['html'] || ''
            }

            vueFilePath = vueFilePath.replace(/\\/g, '/')
            // 记录组件信息
            let importCode = `import ${compName} from '${vueFilePath}'`
            importCodeList['importList'].push(importCode)
            importCodeList['compInfoList'].push(`{ name: '${compName}', item: ${compName} }`)
            importCodeList['compPathList'].push(vueFilePath)

            fs.writeFileSync(path.resolve(vueDirTemp, 'importCompList.js'), getImportStr(importCodeList))
            console.log('缓存importCompList.js文件：', path.resolve(vueDirTemp, 'importCompList.js'))

            return `<demo-block compId="${compName}">
              <template v-slot:showComp>
                  <${compName}></${compName}>
              </template>

              <template v-slot:desc>
                ${descriptionHTML}
              </template>

              <template v-slot:highlight>`
          } else {
            // 结束标签
            return '</template></demo-block>\n'
          }
        }
      })
    }
  }
}

module.exports = {
  pluginOptionsV1
}
